import yaml
import os
import logging
from typing import Dict, Any

class Config:
    """处理应用配置"""
    
    def __init__(self, config_path: str = "config/settings.yaml"):
        self.config_path = config_path
        self.config = self.load_config()
        
    def load_config(self) -> Dict[str, Any]:
        """
        从YAML文件加载配置
        
        Returns:
            配置字典
        """
        try:
            if not os.path.exists(self.config_path):
                return self.create_default_config()
            
            with open(self.config_path, 'r') as f:
                return yaml.safe_load(f)
        except Exception as e:
            logging.error(f"Failed to load config: {str(e)}")
            return self.create_default_config()
            
    def create_default_config(self) -> Dict[str, Any]:
        """
        创建默认配置
        
        Returns:
            默认配置字典
        """
        default_config = {
            "api": {
                "default_model": "irag-1.0",
                "default_url": "https://qianfan.baidubce.com/v2/images/generations",
                "api_key": ""
            },
            "ui": {
                "theme": "light",
                "language": "en"
            },
            "storage": {
                "save_path": "generated_images"
            }
        }
        
        self.save_config(default_config)
        return default_config
        
    def save_config(self, config: Dict[str, Any]) -> None:
        """
        保存配置到YAML文件
        
        Args:
            config: 要保存的配置字典
        """
        try:
            os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
            with open(self.config_path, 'w') as f:
                yaml.dump(config, f)
        except Exception as e:
            logging.error(f"Failed to save config: {str(e)}")
            
    def get(self, key: str, default: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            key: 配置键
            default: 默认值（如果键不存在）
            
        Returns:
            配置值
        """
        return self.config.get(key, default)
        
    def set(self, key: str, value: Any) -> None:
        """
        设置配置值
        
        Args:
            key: 配置键
            value: 配置值
        """
        self.config[key] = value
        self.save_config(self.config)
        
    def update(self, new_config: Dict[str, Any]) -> None:
        """
        更新多个配置值
        
        Args:
            new_config: 新的配置字典
        """
        self.config.update(new_config)
        self.save_config(self.config)